package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.ProductService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public Result<Object> addProduct(@RequestBody JSONObject obj) {
        if (productService.addProduct(obj)) {
            return Result.success();
        } else {
            return Result.error(PRODUCT_ADD_EXCEPTION_CODE, PRODUCT_ADD_EXCEPTION_MESSAGE);
        }
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getProductList(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(productService.getProductList(pageNum, pageSize, condition));
    }

    @GetMapping("/{id}")
    public Result<JSONObject> getProductDetail(@PathVariable("id") Integer id) {
        return Result.success(productService.getProductDetail(id));
    }

    @PutMapping
    public Result<Object> updateProduct(@RequestBody JSONObject obj) {
        if (productService.updateProduct(obj)) {
            return Result.success();
        } else {
            return Result.error(PRODUCT_UPDATE_EXCEPTION_CODE, PRODUCT_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @DeleteMapping("/{id}")
    public Result<Object> deleteProduct(@PathVariable("id") Integer id) {
        if (productService.deleteProduct(id)) {
            return Result.success();
        } else {
            return Result.error(PRODUCT_DELETE_EXCEPTION_CODE, PRODUCT_DELETE_EXCEPTION_MESSAGE);
        }
    }
}
